package com.yonyou.wdt.job;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.dao.JobLogDao;
import com.yonyou.wdt.entity.OpenApiURLEnum;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.model.JobLogModel;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.DateUtils;
import com.yonyou.wdt.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName YsProductToRedisJob
 * @Description YS物料档案信息同步Redis
 * @Author HuangWb
 * @Date 2023/5/12 18:35
 * @Version 1.0
 */
@Component
public class YsBomToRedisJob extends BaseConfig {


    private static Logger logger = LoggerFactory.getLogger(YsBomToRedisJob.class);
    @Resource
    public JobLogDao jobLogDao;
    @Resource
    private YonsuiteService yonsuiteService;


    @XxlJob("YsBomToRedisJob")
    public ReturnT<String> ysProductToRedisJob(String params) throws Exception {
        String param = XxlJobHelper.getJobParam();
        Map<String, Object> wlParam = new HashMap<>();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        if (param != null && !"".equals(param)) {
            List<String> timeRange = Arrays.asList(param.split("\\|"));
            if (timeRange.size() == 2) {
                stringObjectHashMap.put("beganTime", timeRange.get(0));
                stringObjectHashMap.put("endTime", timeRange.get(1));
                wlParam.put("simple", stringObjectHashMap);
            } else {
                wlParam.put("productCode", timeRange.get(0));
            }
        } else {
            // 默认查询前一天的数据
            stringObjectHashMap.put("beganTime", DateUtils.getStartDateBy10m());
            stringObjectHashMap.put("endTime", DateUtils.getEndDateBy10m());
            wlParam.put("simple", stringObjectHashMap);
        }
        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        wlParam.put("pageIndex", 1);
        wlParam.put("pageSize", 100);
        wlParam.put("orgId", "2088056402786385930");
        boolean isNext = true;
        List<Map<String, List<JSONObject>>> list = new ArrayList();
        List<JSONObject> reqAlllist = new ArrayList();
        int error = 0;
        int pageIndex = 1;
        while (true) {
            wlParam.put("pageIndex", pageIndex);
            JSONObject allocationRes = yonsuiteService.ysBomListQuery(wlParam, dto);
            if (allocationRes.getStr("code").equals("200")) {
                if (null != allocationRes.getJSONObject("data") && null != allocationRes.getJSONObject("data").getJSONArray("recordList")) {
                    JSONArray purJSONArray = allocationRes.getJSONObject("data").getJSONArray("recordList");
                    List<JSONObject> reqList = JSONUtil.toList(purJSONArray, JSONObject.class);
                    reqAlllist.addAll(reqList);

                }
            }
            // 调用YS接口保存数据
            this.APICurrentLimiting(OpenApiURLEnum.BOM_LIST_QUERY, 59);
            if (allocationRes.getJSONObject("data").getInt("pageCount") == 0) {
                break;
            }
            if (allocationRes.getJSONObject("data").getInt("pageCount") <= pageIndex) {
                break;
            }
            pageIndex++;
        }
        if (reqAlllist.size() > 0) {
            Map<String, List<JSONObject>> collectMap = reqAlllist.stream().collect(Collectors.groupingBy(json -> json.getStr("code")));
            for (String s : collectMap.keySet()) {
                HashMap<String, List<JSONObject>> stringListHashMap = new HashMap<>();
                stringListHashMap.put(s, collectMap.get(s));
                list.add(stringListHashMap);
            }
            for (Map<String, List<JSONObject>> wlObject : list) {
                Set<String> strings = wlObject.keySet();
                for (String string : strings) {
                    RedisUtils.set(dto.getTenantId() + ":bom:" + string, wlObject.get(string));
                }
            }
            logger.info("租户：{} YS物料清单档案同步Redis完成，共同步物料档案：{}条", dto.getTenantId(), list.size());
            InsertLogger(null, "1", "租户：{" + dto.getTenantId() + "} YS系统物料档案同步Redis完成，共同步物料档案：{" + list.size() + "}条");
        }
        return ReturnT.SUCCESS;
    }

    /**
     * @Author Huangwb
     * @Description 查询YS系统租户动态域名信息
     * @Date 2023/10/30 15:45
     **/
    public ReturnT<String> getYsDynamicDomainName(QueryDto ysQueryDto) {
        try {
            String tenantId = ysQueryDto.getTenantId();  // 租户ID
            if (RedisUtils.get(tenantId + ":DynamicDomainName") == null) {
                // 根据租户ID查询动态域名
                JSONObject dynamicDomainName = yonsuiteService.getDynamicDomainName(null, tenantId);
                if (null != dynamicDomainName && !dynamicDomainName.isEmpty()) {
                    // 将动态域名存入Redis
                    RedisUtils.set(tenantId + ":DynamicDomainName", dynamicDomainName, 86400 * 30);
                } else {
                    logger.error("查询租户【{}】动态域名失败，请重试", tenantId);
                    // insertXxlJobLog(null, "0", "租户：【" + tenantId + "】获取动态域名失败，请稍后重试", jobClassType);
                    InsertLogger(null, "0", "获取动态域名失败");
                    return new ReturnT<>(ReturnT.FAIL_CODE, "查询租户【" + tenantId + "】动态域名失败，请重试");
                }
            }
            // 获取Redis中指定租户动态域名
            JSONObject dynamicDomainNameRedis = (JSONObject) RedisUtils.get(tenantId + ":DynamicDomainName");
            ysQueryDto.setGatewayUrl(dynamicDomainNameRedis.getStr("gatewayUrl"));
            ysQueryDto.setTokenUrl(dynamicDomainNameRedis.getStr("tokenUrl"));
            return null;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "获取动态域名失败：" + e.getMessage());
        }
    }

    /**
     * @return
     * @Author Huangwb
     * @Description 插入数据库日志信息
     * @Date 10:30 2023/9/14
     * @Param
     **/
    private void InsertLogger(String code, String oneL, String mags) {  // 单据编号、是否成功、详细信息
        try {
            JobLogModel jobLogDTO = new JobLogModel();
            jobLogDTO.setJobClass("HYZM010");
            jobLogDTO.setJobCode(code);
            jobLogDTO.setJobTime(new Date());
            jobLogDTO.setJobResult(oneL);
            jobLogDTO.setJobResultMessage(mags);
            jobLogDTO.setJobLogUser("dxroot");
            jobLogDao.insertJobLog(jobLogDTO);
        } catch (Exception e) {
            logger.error("插入日志错误：" + e.getMessage());
        }
    }

}
